package com.xique.blelock.view.AcountManager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.ivin.crop.Log;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xique.blelock.Adapter.UserAdapter;
import com.xique.blelock.Interface.BleListenData;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.BleUtils;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.FingerInfo;
import com.xique.blelock.model.LockAllinfo;
import com.xique.blelock.model.UserOfLockinfo;
import com.xique.blelock.model.UserRole;
import com.xique.blelock.view.BaseActivity;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/12/11.
 */

public class UserListActivity extends BaseActivity implements BleListenData {


    @BindView(R.id.title)
    TextView titile;

    @BindView(R.id.rightimage)
    ImageView rightImage;

    @BindView(R.id.RecyclerView)
    SwipeMenuRecyclerView recyclerView;

    private UserAdapter userAdapter;

    private List<UserOfLockinfo> userOfLockinfos = new ArrayList<>() ;
    private static final int AddUserCmd = 1001;
    private LockAllinfo lockAllinfo;
    //管理员是0号，负管理员是1号 其他市普通用户role=2
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.userlist_activity);
        ButterKnife.bind(this);
        initView();

        initRecyView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BleUtils.setBleListen(this);
    }

    private void initRecyView() {
        // 设置监听器。

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(
                new DefaultItemDecoration(ContextCompat.getColor(this, R.color.divider_primary)));//添加listview分割线


        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        recyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);

        userAdapter = new UserAdapter(userOfLockinfos);
        recyclerView.setAdapter(userAdapter);

//        getUserList();

        userOfLockinfos = lockAllinfo.getLockBandUserList();
        if(userOfLockinfos.size() == 0){
            showToast(this, "暂时没有用户列表");
        }else{
            Collections.sort(userOfLockinfos);
            userAdapter.setDeviceList(userOfLockinfos);
            userAdapter.notifyDataSetChanged();
        }


    }


    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) {
            int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
            int widthlarge = getResources().getDimensionPixelSize(R.dimen.dp_100);
            UserOfLockinfo userOfLockinfo = userOfLockinfos.get(position);
            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;


            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {


                //检查是不是负管理员
                if (lockAllinfo.getRole() == UserRole.commuser) {
                    return;
                }

                if(lockAllinfo.getRole() == UserRole.secondroot && (userOfLockinfo.getRole() == UserRole.root)){
                    return;
                }
                String admin = "";
                if (userOfLockinfos.get(position).getRole() == UserRole.secondroot) {
                    admin = "取消管理员";
                } else {
                    //去用取消了负管理员才能设置管理员
                    boolean isexit = false;
                    for (UserOfLockinfo userOfLockinfo1 : userOfLockinfos) {
                        if (userOfLockinfo1.getRole() == UserRole.secondroot) {
                            isexit = true;
                            break;
                        }
                        //如果
                    }

                    if (!isexit && (userOfLockinfo.getRole() != UserRole.root)) {
                        admin = "设置管理员";
                    }
                }

                if (!TextUtils.isEmpty(admin)) {
                    SwipeMenuItem addItemadmin = new SwipeMenuItem(UserListActivity.this).setBackground(R.color.green_pressed)
                            .setText(admin)
                            .setTextColor(Color.WHITE)
                            .setWidth(widthlarge)
                            .setHeight(height);
                    swipeRightMenu.addMenuItem(addItemadmin); // 添加菜单到右侧。
                    userOfLockinfos.get(position).setMenunum(2);
                }




                SwipeMenuItem deleteItem = new SwipeMenuItem(UserListActivity.this).setBackground(R.drawable.selector_red)
//                        .setImage(R.mipmap.ic_action_delete)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);

                swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。


            }
        }
    };




    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge, int position) {
            menuBridge.closeMenu();
            UserOfLockinfo userOfLockinfo = userOfLockinfos.get(position);

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
//                Toast.makeText(UserListActivity.this, "list第" + position + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
//                        .show();

                if(userOfLockinfo.getMenunum() == 2) {
                    if (menuPosition == 0) {
                        if (userOfLockinfos.get(position).getRole() == 1) {
                            setAdminRole(false, userOfLockinfos.get(position));
                        } else if (userOfLockinfos.get(position).getRole() == 2) {
                            setAdminRole(true, userOfLockinfos.get(position));
                        }
                    } else if (menuPosition == 1) {//准备删除该用户，管理员才有这个权限
                        showdeletDialog(position);

                    }
                }else {//准备删除该用户，管理员才有这个权限
                    showdeletDialog(position);
                }
            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
//                Toast.makeText(UserListActivity.this, "list第" + position + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT)
//                        .show();
            }
        }
    };

    //提示是否需要删除  解除锁和用户的绑定关系
    protected void showdeletDialog(final int position) {
         new MaterialDialog.Builder(this)
                .title("提示")// 标题
                .titleColor(getResources().getColor(R.color.tipstitle))
                .content("确定要退出")// 内容
                .contentColor(Color.BLACK)// 内容颜色
                .positiveText("确定")
                .positiveColorRes(R.color.cologbtnhou)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        deletUserFromDevice(userOfLockinfos.get(position));
                    }
                })
                .negativeText("取消")
                .negativeColorRes(R.color.cancle)
                .show();
    }



    @Override
    protected void initView() {
        super.initView();
        titile.setText("用户列表");

        lockAllinfo = (LockAllinfo) ACache.get(this).getAsObject(Stringkey.lockAllinfo);
        if(lockAllinfo.getRole() == UserRole.commuser)
        {
            rightImage.setVisibility(View.GONE);
        }else{
            rightImage.setVisibility(View.VISIBLE);
        }

    }


    private void getUserList() {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.getUserList(jsonobject.toString()).enqueue(new Callback<NetResult<List<UserOfLockinfo>>>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult<List<UserOfLockinfo>>> call, Response<NetResult<List<UserOfLockinfo>>> response) {


                if(response.body().isSuccess()){
                    userOfLockinfos = response.body().getData();
                    Log.e("获取用户信息Useroflock=== "+ JSON.toJSONString(userOfLockinfos), "");
                    if(userOfLockinfos!=null && userOfLockinfos.size()>0){

                        Collections.sort(userOfLockinfos);

                        userAdapter.setDeviceList(userOfLockinfos);
                        userAdapter.notifyDataSetChanged();
                    }
                    lockAllinfo.setLockBandUserList(userOfLockinfos);
                    ACache.get(UserListActivity.this).put(Stringkey.lockAllinfo, lockAllinfo);

                }else {
                    showToast(UserListActivity.this, "没有获取到指纹列表");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult<List<UserOfLockinfo>>> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });

    }

    //删除绑定设备的普通用户
    private void deletUserFromDevice(UserOfLockinfo userOfLockinfo) {
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put(Stringkey.bandUid, userOfLockinfo.getUid());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        netClient.deleteBandUser(jsonobject.toString()).enqueue(new Callback<NetResult>() {//获取验证码
            @Override
            public void onResponse(Call<NetResult> call, Response<NetResult> response) {

                Log.e("删除用户信息=== "+response, "");
                if(response.body().isSuccess()){
                    getUserList();
                    showToast(UserListActivity.this, "删除用户成功");
                }else {
                    showToast(UserListActivity.this, "删除用户失败");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();

            }
        });
    }

    private void setAdminRole(boolean setadmin, UserOfLockinfo userOfLockinfo){
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();
//        "uid":"a9efb695da394534a9f23d78dffbb06d",
//                "lockId":"lock00001",
//                "token":"84713fe6c4b041a09a7cf601a3e61d4b",
//                "timestamp":"1537940370",
//                "bandUid":"xxx"
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("lockId", BleUtils.getBleDevice().getMac().replace(":", ""));//E0:4C:63:6D:82:43
            jsonobject.put("bandUid", userOfLockinfo.getUid());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog();
        if(setadmin)
        {
            netClient.setAdmin(jsonobject.toString()).enqueue(netResultCall);
        }else{
            netClient.cancleAdmin(jsonobject.toString()).enqueue(netResultCall);
        }

    }
    private Callback<NetResult>  netResultCall = new Callback<NetResult>() {
        @Override
        public void onResponse(Call<NetResult> call, Response<NetResult> response) {
            hideProgressDialog();
            Log.e("获取用户信息Useroflock=== "+ JSON.toJSONString(response.body()), "");
            if(response.body().isSuccess()){
                showToast(UserListActivity.this, "设置管理员成功 ");
                getUserList();


            }else {
                showToast(UserListActivity.this, "设置管理员失败"+response.body().getMessage());
            }

        }

        @Override
        public void onFailure(Call<NetResult> call, Throwable t) {
            t.printStackTrace();
            hideProgressDialog();

        }
    };

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }

    @OnClick(R.id.rightimage)
    public void addUser(){
        Intent intent = new Intent(this, AddUserActitivy.class);
        intent.putParcelableArrayListExtra(Stringkey.USER_LIST, (ArrayList<? extends Parcelable>) userOfLockinfos);
        startActivityForResult(intent,AddUserCmd);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == AddUserCmd && resultCode==RESULT_OK){
            getUserList();
        }
    }

    @Override
    public void didReciveData(byte[] data) {

    }
}
